import router, { asyncRouterMap, constantRouterMap } from '@/router'
import { store } from '@fl/store/index'
import {
    flatMultiLevelRoutes,
    generateRoutesByFrontEnd,
} from '@fl/utils/routerHelper'
import { cloneDeep } from 'lodash-es'
import { defineStore } from 'pinia'
import { compositeMenuByEnterpriseType, generateRoutesByEnterpriseType, generateRoutesByServer } from './helper'
import { useUserStore } from '@fl/store/modules/user'
import { getJointAppKey } from '@fl/logics/jointAuth'
import { getCompanyCard } from '@fl/api/joint-api'

type IHeaderMenuItem = {
    label: string
    path: string
}

export type PermissionState = {
    addRouters: AppRouteRecordRaw[]
    isAddRouters: boolean
    headerMenu: IHeaderMenuItem[]
    menuTabRouters: AppRouteRecordRaw[]
    // sidebar 菜单路径前缀
    pathPrefix: string
    routers: AppRouteRecordRaw[]
    // 大系统下的分片路由
    sliceRouters: AppRouteRecordRaw[]
}

// export const cardTypeEnum = {
//     1: {
//         label: '联合运营平台',
//         path: '/joint',
//     },
//     2: {
//         label: '武汉好房',
//         path: '/good-house',
//     },
//     // 3: {
//     //     label: '武汉新房',
//     //     path: '/new-house',
//     // },
// } as const

const pathEnum = {
    oqM7asRJzefjj8o4: '/joint',
    ZpLX6IoNqLyGe3Sw: '/new-house',
    eKLaSSfIn7Ta9rcz: '/good-house-new',
}

const defaultMenu = [{
    label: '联合运营平台',
    path: '/joint',
    appKey: getJointAppKey(),
    appId: '18',
    id: '1060',
},
// {
//     label: '武汉好房wujie',
//     path: '/good-house',
//     appKey: 'eKLaSSfIn7Ta9rcz',
//     appId: '19',
//     id: '1061',
// }
]

export const usePermissionStore = defineStore('permission', {
    actions: {
        generateHeaderMenu(): void {
            const userStore = useUserStore()
            const userInfo = userStore.getUserInfo
            // console.log('🚀 ~ generateHeaderMenu ~ userInfo:', userInfo)
            const { userFlag, userStep } = userInfo as any
            // 企业管理员进来就先创建企业，用的是前段写的路由
            if (userFlag === '2' && ['1', '2'].includes(userStep)) {
                this.headerMenu = []
                return
            }
            // 把联合运营固定到第一个
            // const appRoles = userStore.getUserInfo?.iamAccountVo?.appRoles?.filter(item => item.appKey !== getJointAppKey())

            getCompanyCard().then((res) => {
                // console.log('🚀 ~ getCompanyCard ~ res:', res)
                if (res?.length) {
                    const list = res?.map(item => ({
                        label: `${item?.cardName}`,
                        path: pathEnum[item.appKey],
                        appKey: `${item.appKey}`,
                    })) || []
                    this.headerMenu = [...defaultMenu, ...list] || []
                }
                else {
                    this.headerMenu = defaultMenu
                }
            })
        },
        generateRoutes(
            type?: 'frontEnd' | 'server' | 'static',
            routers?: AppCustomRouteRecordRaw[] | string[],
        ): Promise<AppRouteRecordRaw[]> {
            return new Promise<AppRouteRecordRaw[]>((resolve) => {
                let routerMap: AppRouteRecordRaw[] = []
                if (type === 'server') {
                    routerMap = generateRoutesByServer(routers)
                }
                else if (type === 'frontEnd') {
                    // 模拟前端过滤菜单
                    routerMap = generateRoutesByFrontEnd(cloneDeep(asyncRouterMap), routers as string[])
                }
                else {
                    // 直接读取静态路由表
                    // routerMap = generateRoutesByEnterpriseType()
                    routerMap = cloneDeep(asyncRouterMap)
                }

                // 动态路由，404一定要放到最后面
                this.addRouters = routerMap.concat([
                    {
                        meta: {
                            breadcrumb: false,
                            hidden: true,
                        },
                        name: '404Page',
                        path: '/:path(.*)*',
                        redirect: '/404',
                    },
                ])

                // 渲染菜单的所有路由
                this.routers = cloneDeep(constantRouterMap).concat(routerMap)
                console.log('this.routers', this.routers)
                resolve(this.addRouters)
            })
        },
        setIsAddRouters(state: boolean): void {
            this.isAddRouters = state
        },
        setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
            this.menuTabRouters = routers
        },
        // 设置分片的路由
        setSliceRouters(path?: string): void {
            if (path) {
                this.pathPrefix = path

                // （新）
                const target = this.getRouters.find(item => item.path === path)
                this.sliceRouters = target?.children ?? []
                router.push(path)
            }
        },
        setHeadMenuRouters(): void {
            this.sliceRouters = this.addRouters
        },
    },
    getters: {
        getAddRouters(): AppRouteRecordRaw[] {
            const newRouters = flatMultiLevelRoutes(cloneDeep(this.addRouters))
            // console.log('🚀 ~ getAddRouters ~ this.addRouters:', this.addRouters)
            // console.log('🚀 ~ getAddRouters ~ newRouters:', newRouters)
            return newRouters
        },
        getIsAddRouters(): boolean {
            return this.isAddRouters
        },
        getMenuTabRouters(): AppRouteRecordRaw[] {
            return this.menuTabRouters
        },
        getPathPrefix(): string {
            return this.pathPrefix
        },
        getRouters(): AppRouteRecordRaw[] {
            return this.routers
        },
        getSliceRouters(): AppRouteRecordRaw[] {
            return this.sliceRouters
        },
    },
    persist: {
        paths: ['routers', 'addRouters', 'menuTabRouters'],
    },
    state: (): PermissionState => ({
        addRouters: [],
        isAddRouters: false,
        menuTabRouters: [],
        pathPrefix: '',
        routers: [],
        headerMenu: [],
        // 大系统下的分片路由
        sliceRouters: [],
    }),
})

export function usePermissionStoreWithOut() {
    return usePermissionStore(store)
}
